package com.kingyun.gpsinspection.purificationservice.services.jsm.innerservice.impl.property;

import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.api.common.utils.enums.RespCodeEnum;
import com.google.common.collect.Maps;
import com.kingyun.gpsinspection.purificationservice.common.constant.BackMessage;
import com.kingyun.gpsinspection.purificationservice.common.enums.TreeIconSkinEnum;
import com.kingyun.gpsinspection.purificationservice.common.utils.CommonUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.jsm.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.device.JsmDeviceService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.employee.JsmEmployeeService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.organization.JsmOrganizationService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.property.JsmEntityPropertyService;
import com.kingyun.gpsinspection.purificationservice.facade.service.jsm.reportinfoItem.JsmReportinfoItemService;
import com.kingyun.gpsinspection.purificationservice.services.jsm.innerservice.util.OrgTreeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by huangxueqian on 2017/2/16/016.
 * 实体特性值服务实现类
 */

public class JsmEntityPropertyServiceImpl implements JsmEntityPropertyService {

    @Autowired
    private EntityProMapper entityProMapper ;

    @Autowired
    private JsmReportinfoItemService reportinfoItemService;


    @Autowired
    private EntityTypeProMapper entpProMapper;


    @Autowired
    private EntityPropertyMapMapper entityPropertyMapMapper;


    @Autowired
    private JsmOrganizationMapper organizationMapper;

    @Autowired
    private JsmDeviceService jsmDeviceService ;

    @Autowired
    private JsmOrganizationService organizationService ;
    @Autowired
    private DeviceMapper deviceMapper;


    @Override
    public Map<String, Object> table(EntityPro entityPro) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("total",entityProMapper.queryEntityProCount(entityPro))  ;
        resMap.put("rows",entityProMapper.queryEntityProList(entityPro))  ;
        return resMap;
    }

    @Override
    public EntityPro selectByPrimaryKey(String propertyId) throws Exception {
        return entityProMapper.selectByPrimaryKey(propertyId);
    }

    /**
     * 根据实体id查询特性值
     * @param list
     * @return
     */
    @Override
    public List<EntityPro> selectByEntityIds(List<String> list,String orgId) {
        Map map = new HashMap<>();
        map.put("list",list);
        map.put("orgId",orgId);
        return entityProMapper.selectByEntityIds(map);
    }

    /**
     * 保存生产实体特性
     *
     * @param entityPros
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public Map<String,Object> addEntityPro(List<EntityPro> entityPros,Employee employee) throws Exception {
        Map<String,Object> result= Maps.newHashMap();
        String creatorId = employee.getEmployeeId();
        try{
            for(EntityPro entityPro:entityPros){
                if(entityPro.getEntpPropertyId()!=null){
                    entityPro.setCreator(creatorId);
                    entityPro.setCreateTime(null);
                    entityPro.setModifyer(creatorId);
                    entityPro.setModifyTime(CommonUtil.getTimeString());
                    entityProMapper.updateByPrimaryKeySelective(entityPro);
                    clonePro(entityPro.getEntityTypeId(),employee);
                }else{
                    entityPro.setEntpPropertyId(entityPro.getDevicePropertyId());
                    entityPro.setDevicePropertyId(UniqueUtil.uuid16());
                    entityPro.setCreator(creatorId);
                    entityPro.setStatus(new BigDecimal(0));
                    entityPro.setEntityTypeId(entityPro.getEntityTypeId());
                    entityPro.setCreateTime(CommonUtil.getTimeString());
                    entityPro.setModifyer(creatorId);
                    entityPro.setModifyTime(CommonUtil.getTimeString());
                    entityProMapper.insert(entityPro);
                }
            }
            result.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
            result.put("msg", BackMessage.ADD_OK);
            return result;
        }catch (Exception e){
            throw  new RuntimeException("提交失败");
        }

    }


    /**
     * 从生产实体类型特性中克隆到所属设备特性中
     * @param entityTypeId 实体类型ID
     * @throws Exception
     * 根据实体ID， 查询生产实体类型，根据生产实体类型查询，生产实体类型特性值，然后将生产实体类型特性值，插入到实体特性值
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String, Object> clonePro(String entityTypeId,Employee employee) throws Exception {
        Map<String, Object> resMap = new HashMap<>();
            List<EntityTypePro> entityTypePList = entpProMapper.selectByEnTypeId(entityTypeId);
            if (entityTypePList == null) {
                resMap.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
                resMap.put("msg", "生产实体类型特性值不存在！");
            } else {
                for (EntityTypePro entityTypePro : entityTypePList) {
                    EntityPro entityPro = new EntityPro();
                    entityPro.setEntityId(entityTypeId);
                    entityPro.setEntpPropertyId(entityTypePro.getDevicePropertyId());
                    entityPro.setStatus(BigDecimal.valueOf(0D));
                    /**
                     * 遍历特性
                     * 实体特性是否已经存在，已经存在则，不进行复制，如不存在则进行插入操作
                     */
                    EntityPro   entityProIs = entityProMapper.selectByEntityPro(entityPro);
                    if(entityProIs == null){
                        /**
                         *插入特性值
                         */
                        entityPro.setDevicePropertyId(UniqueUtil.uuid16());
                        if(entityTypePro.getPropertyName()!=null)entityPro.setPropertyName(entityTypePro.getPropertyName());
                        if(entityTypePro.getPropertyValue()!=null)entityPro.setPropertyValue(entityTypePro.getPropertyValue());
                        if(entityTypePro.getPropertyUnit()!=null)entityPro.setPropertyUnit(entityTypePro.getPropertyUnit());
                        entityPro.setEntpPropertyId(entityTypePro.getDevicePropertyId());
                        entityPro.setEntityTypeId(entityTypeId);
                        entityPro.setPropertyType(entityTypePro.getPropertyType());
                        entityPro.setEntityId(entityTypeId);
                        entityPro.setStatus(entityTypePro.getStatus());
                        entityPro.setCreator(employee.getEmployeeId());
                        entityPro.setModifyer(employee.getEmployeeId());
                        entityPro.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                        entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
                        entityProMapper.insertSelective(entityPro);
                        resMap.put("result",RespCodeEnum.RESP_CODE_ENUM_true.code());
                    }

                }

                resMap.put("state",RespCodeEnum.RESP_CODE_ENUM_true.code());
                resMap.put("msg","实体特性克隆成功！");
            }


        return resMap;

    }

    /**
     * @param entityId
     * 查询实体 查询实体特性值列表
     */
    @Override
    public List<EntityPro> selectEntityProListByEntityId(String entityId) throws Exception {
        List<EntityPro> entityProList = new ArrayList<>();
        EntityPro entityPro = new EntityPro();
        entityPro.setEntityId(entityId);
        entityProList =  entityProMapper.getEntityProByEntityId(entityId);
        return entityProList ;
    }

    /**
     * 删除生产实体特性
     *
     * @param entityPropertyId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Map<String,Object> delEntityPropertyById(String entityPropertyId) {
        Map<String,Object> result=Maps.newHashMap();
        int rowCount = entityProMapper.delEnProperty(entityPropertyId);
        if(rowCount>0){
            result.put("state", RespCodeEnum.RESP_CODE_ENUM_true.code());
            result.put("msg", "删除特性值成功!");
        }else{
            result.put("state", RespCodeEnum.RESP_CODE_ENUM_false.code());
            result.put("msg", "删除特性值失败!");
        }
        return result;
    }

    /**
     * 根据特性值ID 查询特性值以及特性值其他信息
     *
     * @param propertyId
     * @return
     * @throws Exception
     */
    @Override
    public EntityPro queryByPropertyId(String propertyId) throws Exception {
        return entityProMapper.queryByPropertyId(propertyId);
    }

    /**
     * @param entityPro 特性值管理列表,带有特性值其他信息
     * @param employee
     * @return 特性值对象
     */
    @Override
    public JSONObject propertyTable(EntityPro entityPro, Employee employee) throws Exception {
        // 使用组织层级 进行权限设置控制
        entityPro.setOrgLevelId(employee.getOrgId());
        //
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total", entityProMapper.queryEntityProTableCount(entityPro));
        jsonObject.put("rows", entityProMapper.queryEntityProTableList(entityPro));
        return jsonObject;
    }

    /**
     * 保存特性值
     *
     * @param entityPro
     * @param employeeVo
     */
    @Override
    public Integer saveProperty(EntityPro entityPro, EmployeeVo employeeVo) throws Exception {
        int resInt = 0;
        entityPro.setCreator(employeeVo.getEmployeeId());
        entityPro.setStatus(new BigDecimal(0));
        //entityPro.setEntityTypeId(entity.getEnTypeId());
        entityPro.setCreateTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
        entityPro.setModifyer(employeeVo.getEmployeeId());
        entityPro.setModifyTime(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
        // 是否存在特性值Id=""
        if (StringUtils.isNotEmpty(entityPro.getDevicePropertyId())) {
            entityProMapper.updateByPrimaryKeySelective(entityPro);
            // 修改
        } else {
            entityPro.setDevicePropertyId(UniqueUtil.uuid16());
            // 新增
            resInt = entityProMapper.insertSelective(entityPro);
        }

        if(StringUtils.isEmpty(entityPro.getMapId())){
            reportinfoItemService.insertPropertyMap(entityPro, employeeVo);
        }else{
            EntityPropertyMap record = new EntityPropertyMap();
            record.setMapId(entityPro.getMapId());
            // 修改绑定
            if(StringUtils.isNotEmpty(entityPro.getReportInfoId()) &&StringUtils.isNotEmpty(entityPro.getItemId())){
                record.setReportinfoId(entityPro.getReportInfoId());
                record.setDevicePropertyId(entityPro.getDevicePropertyId());
                record.setReportItem(entityPro.getItemId());
                record.setmUpdate(DateUtil.DateToString(new Date(),DateStyle.YYYY_MM_DD_HH_MM));
                record.setmOperator(employeeVo.getEmployeeId());
                entityPropertyMapMapper.updateByPrimaryKeySelective(record);
            }else{
                // 取消绑定 ， 然后删除绑定
                entityPropertyMapMapper.unBindDataItem(entityPro.getDevicePropertyId());
            }
        }

        return resInt;
    }




    /**
     * @param employee 人员信息
     * @param orgId    组织机构
     * @param keyword  搜索关键字
     */
    @Override
    public List<Ztree> loadOrgZtreeByDevice(Employee employee, String orgId, String keyword) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        List<DeviceVo> deviceVOList = new ArrayList<>();
        // 加载 组织机构 并可以异步加载
        if(StringUtils.isEmpty(orgId) && StringUtils.isEmpty(keyword)){
            List<Organization> organizationList = organizationService.getOrganizationList(employee,"1","6");
            List<Ztree> listOrg = organizationService.setZtree(organizationList);
            if(listOrg != null && listOrg.size() > 0){
                // 查询下面的设备 或者 下面的特性值 进行设置ajax
                for(Ztree ztree :listOrg){
                    // 查询特性
                    // 查询设备
                    List<EntityPro> entityProList = selectEntityProListByEntityId(ztree.getId());
                    List<DeviceVo> deviceVOListIsHave = jsmDeviceService.getDevices(ztree.getId());
                    if(entityProList != null && entityProList.size() > 0 ){
                        ztree.setIsParent(true);
                    }else if(deviceVOListIsHave != null && deviceVOListIsHave.size() > 0){
                        ztree.setIsParent(true);
                    }else{
                        ztree.setIsParent(false);
                    }
                    ztree.setOpen(false);
                    ztreeList.add(ztree);
                }
            }
        }
        // 进行异步加载
        if(StringUtils.isNotEmpty(orgId) && StringUtils.isEmpty(keyword)){
            deviceVOList.addAll(jsmDeviceService.getDevices(orgId));
        }
        // 查询全部
        if(StringUtils.isNotEmpty(keyword)){
            /**
             * 根据当前人员组织机构 和 当前的设备名称 或者编号进行查询
             */
            List<Organization> organizationList = organizationService.getOrganizationList(employee,"1","6");
            List<DeviceVo> deviceVOListKeyword = jsmDeviceService.queryDeviceVoByOrgsKeyword(organizationList,keyword);
            deviceVOList.addAll(deviceVOListKeyword);
        }
        if(deviceVOList != null && deviceVOList.size() > 0){
            for(DeviceVo deviceVO : deviceVOList){
                Ztree ztree = new Ztree();
                ztree.setId(deviceVO.getDeviceId());
                ztree.setpId(deviceVO.getOrgId());
                ztree.setName(deviceVO.getDeviceName()+"--"+deviceVO.getDeviceCode());
                ztree.setIconSkin(TreeIconSkinEnum.ICON_ENTITY.getDesc());
                ztree.setOpen(true);
                ztree.setIsParent(false);
                ztreeList.add(ztree);
            }
        }
        //打补丁 , 查询当前设备的组织机构 进行向上查询!
        if(StringUtils.isNotEmpty(keyword)){
            if(deviceVOList != null && deviceVOList.size() > 0 ){
                List<String> orgIdList = new ArrayList<>();
                for(DeviceVo deviceVO : deviceVOList){
                    orgIdList.add(deviceVO.getOrgId()) ;
                }
                List<Organization>  list =  organizationService.selectBottomToTopOrgList(orgIdList,employee);
                if(list != null && list.size() > 0){
                    try {
                        ztreeList.addAll(organizationService.setZtree(list));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return ztreeList ;
    }

    /**
     * 获取当前组织机构下的特性值 和 设备下的特性值 可以进行查询当前下的特性值
     *
     * @param employee
     * @param orgId
     * @param keyword
     */
    @Override
    public List<Ztree> loadOrgZtreeByDeviceProperty(Employee employee, String orgId, String keyword) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        List<DeviceVo> deviceVOList = new ArrayList<>();
        // 加载 组织机构 并可以异步加载
        if(StringUtils.isEmpty(orgId) && StringUtils.isEmpty(keyword)){
            List<Organization> organizationList = organizationService.getOrganizationList(employee,"1","6");
            List<Ztree> listOrg = organizationService.setZtree(organizationList);
            if(listOrg != null && listOrg.size() > 0){
                // 查询下面的设备 或者 下面的特性值 进行设置ajax
                for(Ztree ztree :listOrg){
                    // 查询特性
                    // 查询设备
                    List<EntityPro> entityProList = selectEntityProListByEntityId(ztree.getId());
                    List<DeviceVo> deviceVOListIsHave = jsmDeviceService.getDevices(ztree.getId());
                    if(entityProList != null && entityProList.size() > 0 ){
                        ztree.setIsParent(true);
                    }else if(deviceVOListIsHave != null && deviceVOListIsHave.size() > 0){
                        ztree.setIsParent(true);
                    }else{
                        ztree.setIsParent(false);
                    }
                    ztree.setOpen(false);
                    ztreeList.add(ztree);
                }
            }
        }
        // 进行异步加载
        if(StringUtils.isNotEmpty(orgId) && StringUtils.isEmpty(keyword)){
            deviceVOList.addAll(jsmDeviceService.getDevices(orgId));
            // 查询特心智
            List<EntityPro> entityProList = selectEntityProListByEntityId(orgId);
            ztreeList.addAll(offsetEntityPro(entityProList));
        }
        if(deviceVOList != null && deviceVOList.size() > 0){
            for(DeviceVo deviceVO : deviceVOList){
                Ztree ztree = new Ztree();
                ztree.setId(deviceVO.getDeviceId());
                ztree.setpId(deviceVO.getOrgId());
                ztree.setName(deviceVO.getDeviceName()+"--"+deviceVO.getDeviceCode());
                ztree.setIconSkin(TreeIconSkinEnum.ICON_ENTITY.getDesc());
                ztree.setOpen(true);
                ztree.setIsParent(false);
                List<EntityPro> entityProList = selectEntityProListByEntityId(deviceVO.getDeviceId());
                if(entityProList!=null && entityProList.size() > 0){
                    ztreeList.addAll(offsetEntityPro(entityProList));
                    ztreeList.add(ztree);
                }
            }
        }
        return ztreeList;
    }

    /**
     * @param   entityPros
     * @return  将特性值列表转成数据项列表
     */

    private  List<Ztree> offsetEntityPro(List<EntityPro> entityPros) throws Exception {
        List<Ztree> entityProList = new ArrayList<>();
        if(entityPros != null && entityPros.size() >0 ){
            for(EntityPro entityPro : entityPros){
                Ztree ztree = new Ztree();
                ztree.setId(entityPro.getDevicePropertyId());
                ztree.setpId(entityPro.getEntityId());
                ztree.setName(entityPro.getPropertyName());
                ztree.setIconSkin(TreeIconSkinEnum.ICON_DEVICE_CHARA.getDesc());
                ztree.setIsParent(false);
                ztree.setOpen(true);
                entityProList.add(ztree);
            }
        }
        return entityProList ;
    }

    /**
     * 根据orgId查询集合
     *
     * @param orgId
     * @return
     * @Author 卢曼成
     * @CreateDateTime 2017/6/6 13:59
     */
    @Override
    public List<Ztree> selectByOrgEntity(String orgId) {
        if (StringUtils.isEmpty(orgId)) {
            return null;
        }
        // 组织
        List<Organization> orgList = organizationMapper.queryEntityPropertyOrgs(orgId);
        if (orgList != null && orgList.size() > 0) {
            // 设备
            List<DeviceVo> deviceVoList = deviceMapper.queryDevicePropertyByOrgs(orgList);
            List<Ztree> ztreeList = new ArrayList<Ztree>();
            Ztree demo;
            for (Organization org : orgList) {
                demo = new Ztree();
                demo.setId(org.getOrgId());
                demo.setpId(org.getParentOrgId());
                demo.setName(org.getOrgName());
                demo.setOrgLevel(org.getOrgLevelId());
                int levelId = Integer.parseInt(org.getOrgLevelId());
                demo.setIconSkin(OrgTreeUtil.iconSkin(levelId));
                demo.setIsParent(true);
                demo.setOpen(true);
                ztreeList.add(demo);
            }
            if( deviceVoList != null && deviceVoList.size() > 0 ){
                for (DeviceVo deviceVo:deviceVoList){
                    demo = new Ztree();
                    demo.setObj(deviceVo);
                    demo.setId(deviceVo.getDeviceId());
                    demo.setpId(deviceVo.getOrgId());
                    demo.setName(deviceVo.getDeviceName());
                    demo.setIconSkin(TreeIconSkinEnum.ICON_DEVICE.getDesc());
                    demo.setOpen(true);
                    ztreeList.add(demo);
                }
                List<EntityPro> list = entityProMapper.queryPropertyByDeviceIds(deviceVoList);
                if (list != null && list.size() > 0) {
                    for (EntityPro ep : list) {
                        demo = new Ztree();
                        demo.setObj(ep);
                        demo.setId(ep.getDevicePropertyId());
                        demo.setpId(ep.getDeviceId());
                        demo.setName(ep.getPropertyName());
                        demo.setIconSkin(TreeIconSkinEnum.ICON_DEVICE_CHARA.getDesc());
                        demo.setOpen(false);
                        ztreeList.add(demo);
                    }
                }
            }
            return ztreeList;
        }
        return null;
    }


}
